{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "#from __future__ import absolute_import\n",
    "#from __future__ import division\n",
    "#from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-c588990fafe9>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting ./data/t10k-images-idx3-ubyte.gz\n",
      "Extracting ./data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From C:\\Users\\wangruipeng\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = './data/'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W = tf.Variable(tf.zeros([784, 10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "y = tf.matmul(x, W) + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-5-bf86c3447efc>:11: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See @{tf.nn.softmax_cross_entropy_with_logits_v2}.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.GradientDescentOptimizer(1).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train\n",
    "for _ in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9198\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 多隐层\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 隐层神经元数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自定义多隐含层模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy after  200 train steps:\ttrain set: 0.91511\ttest set: 0.91680\ttime used in this loop: 1.93 \n",
      "Accuracy after  400 train steps:\ttrain set: 0.94011\ttest set: 0.93880\ttime used in this loop: 1.68 \n",
      "Accuracy after  600 train steps:\ttrain set: 0.94516\ttest set: 0.94540\ttime used in this loop: 1.61 \n",
      "Accuracy after  800 train steps:\ttrain set: 0.95756\ttest set: 0.95360\ttime used in this loop: 1.70 \n",
      "Accuracy after 1000 train steps:\ttrain set: 0.96435\ttest set: 0.96100\ttime used in this loop: 1.59 \n",
      "Accuracy after 1200 train steps:\ttrain set: 0.97027\ttest set: 0.96500\ttime used in this loop: 1.58 \n",
      "Accuracy after 1400 train steps:\ttrain set: 0.96871\ttest set: 0.96390\ttime used in this loop: 1.68 \n",
      "Accuracy after 1600 train steps:\ttrain set: 0.97520\ttest set: 0.96750\ttime used in this loop: 1.57 \n",
      "Accuracy after 1800 train steps:\ttrain set: 0.97542\ttest set: 0.96610\ttime used in this loop: 1.68 \n",
      "Accuracy after 2000 train steps:\ttrain set: 0.97782\ttest set: 0.97130\ttime used in this loop: 1.55 \n",
      "Accuracy after 2200 train steps:\ttrain set: 0.97400\ttest set: 0.96490\ttime used in this loop: 1.60 \n",
      "Accuracy after 2400 train steps:\ttrain set: 0.98055\ttest set: 0.97440\ttime used in this loop: 1.80 \n",
      "Accuracy after 2600 train steps:\ttrain set: 0.98025\ttest set: 0.97320\ttime used in this loop: 1.57 \n",
      "Accuracy after 2800 train steps:\ttrain set: 0.98247\ttest set: 0.97560\ttime used in this loop: 1.55 \n",
      "Accuracy after 3000 train steps:\ttrain set: 0.98273\ttest set: 0.97430\ttime used in this loop: 1.71 \n",
      "Accuracy after 3200 train steps:\ttrain set: 0.98315\ttest set: 0.97160\ttime used in this loop: 1.56 \n",
      "Accuracy after 3400 train steps:\ttrain set: 0.98235\ttest set: 0.97220\ttime used in this loop: 1.58 \n",
      "Accuracy after 3600 train steps:\ttrain set: 0.98227\ttest set: 0.97230\ttime used in this loop: 1.67 \n",
      "Accuracy after 3800 train steps:\ttrain set: 0.98542\ttest set: 0.97500\ttime used in this loop: 1.58 \n",
      "Accuracy after 4000 train steps:\ttrain set: 0.98616\ttest set: 0.97430\ttime used in this loop: 1.67 \n",
      "Accuracy after 4200 train steps:\ttrain set: 0.98555\ttest set: 0.97470\ttime used in this loop: 1.57 \n",
      "Accuracy after 4400 train steps:\ttrain set: 0.98635\ttest set: 0.97500\ttime used in this loop: 1.60 \n",
      "Accuracy after 4600 train steps:\ttrain set: 0.98820\ttest set: 0.97550\ttime used in this loop: 1.66 \n",
      "Accuracy after 4800 train steps:\ttrain set: 0.98660\ttest set: 0.97600\ttime used in this loop: 1.57 \n",
      "Accuracy after 5000 train steps:\ttrain set: 0.98525\ttest set: 0.97170\ttime used in this loop: 1.63 \n",
      "Accuracy after 5200 train steps:\ttrain set: 0.98660\ttest set: 0.97520\ttime used in this loop: 1.67 \n",
      "Accuracy after 5400 train steps:\ttrain set: 0.98984\ttest set: 0.97850\ttime used in this loop: 1.63 \n",
      "Accuracy after 5600 train steps:\ttrain set: 0.98802\ttest set: 0.97860\ttime used in this loop: 1.73 \n",
      "Accuracy after 5800 train steps:\ttrain set: 0.99040\ttest set: 0.97880\ttime used in this loop: 1.89 \n",
      "Accuracy after 6000 train steps:\ttrain set: 0.99051\ttest set: 0.97840\ttime used in this loop: 1.63 \n",
      "Accuracy after 6200 train steps:\ttrain set: 0.99091\ttest set: 0.97770\ttime used in this loop: 1.82 \n",
      "Accuracy after 6400 train steps:\ttrain set: 0.98816\ttest set: 0.97630\ttime used in this loop: 1.70 \n",
      "Accuracy after 6600 train steps:\ttrain set: 0.98633\ttest set: 0.97370\ttime used in this loop: 1.66 \n",
      "Accuracy after 6800 train steps:\ttrain set: 0.98927\ttest set: 0.97550\ttime used in this loop: 1.76 \n",
      "Accuracy after 7000 train steps:\ttrain set: 0.98938\ttest set: 0.97600\ttime used in this loop: 1.63 \n",
      "Accuracy after 7200 train steps:\ttrain set: 0.99064\ttest set: 0.97610\ttime used in this loop: 1.63 \n",
      "Accuracy after 7400 train steps:\ttrain set: 0.99218\ttest set: 0.98040\ttime used in this loop: 1.97 \n",
      "----------final result----------\n",
      "Accuracy of train set: 0.99218, Accuracy of test set: 0.98040\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "graph = tf.Graph()\n",
    "t = time.time()\n",
    "with graph.as_default() as g:\n",
    "    with tf.Session(graph=g) as sess:\n",
    "        lr = tf.Variable(0.001, dtype=tf.float32)  \n",
    "        \n",
    "        x = tf.placeholder(tf.float32, [None, 784])\n",
    "        W = tf.Variable(tf.random_uniform([784, 384], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        b = tf.Variable(tf.random_uniform([384], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        l1 = tf.matmul(x, W) + b\n",
    "        l1 = tf.nn.relu6(l1)\n",
    "        #y = l1\n",
    "\n",
    "        W1 = tf.Variable(tf.random_uniform([384, 192], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        b1 = tf.Variable(tf.random_uniform([192], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        l2 = tf.matmul(l1, W1) + b1\n",
    "        l2 = tf.nn.relu(l2)\n",
    "        #y = tf.nn.softmax(l2)\n",
    "\n",
    "        W2 = tf.Variable(tf.random_uniform([192, 10], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        b2 = tf.Variable(tf.random_uniform([10], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        l3 = tf.matmul(l2, W2) + b2\n",
    "        y = tf.nn.softmax(l3)\n",
    "\n",
    "        #W3 = tf.Variable(tf.random_uniform([64, 10], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        #b3 = tf.Variable(tf.random_uniform([10], minval=-0.1, maxval=0.1, dtype=tf.float32))\n",
    "        #y = tf.matmul(l3, W3) + b3\n",
    "        #y = tf.nn.softmax(y)\n",
    "        \n",
    "        y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "        cross_entropy = tf.reduce_mean(\n",
    "            tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "        train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)\n",
    "        \n",
    "        init_op = tf.global_variables_initializer()\n",
    "        sess.run(init_op)\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        for _ in range(10000):\n",
    "            batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "            sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})           \n",
    "            if _%200 == 0:\n",
    "                if _ == 0:continue\n",
    "                print(\"Accuracy after %4d train steps:\" %_, end='\\t')\n",
    "                print(\"train set: %.5f\" %sess.run(accuracy, feed_dict={x: mnist.train.images,\n",
    "                                                      y_: mnist.train.labels}), end='\\t')\n",
    "                print(\"test set: %.5f\" %sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                                      y_: mnist.test.labels}), end='\\t') \n",
    "                print(\"time used in this loop: %.2f \"%(time.time()-t))\n",
    "                t = time.time()\n",
    "                if sess.run(accuracy, feed_dict={\n",
    "                    x: mnist.test.images, y_: mnist.test.labels\n",
    "                }) > 0.98:\n",
    "                    break\n",
    "        print(\"----------final result----------\")\n",
    "        print(\"Accuracy of train set: %.5f\" %sess.run(accuracy, feed_dict={x: mnist.train.images,\n",
    "                                              y_: mnist.train.labels}), end= ', ')\n",
    "        print(\"Accuracy of test set: %.5f\" %sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                              y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    " sess.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
